//
//  HICComposeViewController.swift
//  vibo
//
//  Created by jht-seven on 16/7/3.
//  Copyright © 2016年 jht-seven. All rights reserved.
//

import UIKit

class HICComposeViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
        //添加控件
        view.addSubview(composeTextView)
        view.addSubview(composeToolbar)
        
        composeTextView.addSubview(pictureView)
        
        //添加约束
        //在ios7以后 系统检测出you导航栏 textView的文字下移
        composeTextView.snp_makeConstraints { (make) in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        
        composeToolbar.snp_makeConstraints { (make) in
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        
        pictureView.snp_makeConstraints { (make) in
            make.leading.equalTo(composeTextView).offset(10)
            make.top.equalTo(composeTextView).offset(100)
            make.size.equalTo(CGSize(width: SCREENW - 20, height: SCREENW - 20))
        }
        
        //弹出相册
        pictureView.composePictureViewClosure = {[weak self] ()->() in
            self?.selectImages()
            
        }
        
        //监听composeToolbar中的按钮点击
        composeToolbar.closure = {[weak self] (type: HICComposeToolbarType) ->() in
            switch type{
            case .Picture:
                self?.selectImages()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emotion:
                print("表情")
                self?.switchKeyboard()
            case .Add:
                print("+")
                
            }
            
        }
        
        
        //通过系统通知监听键盘
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    
    // 监听键盘frame改变
    func keyboardWillChangeFrame(noti: NSNotification){
//        print(noti.object)
//        print(noti)
        // NSRect mac开发中用得 我们移动端开发CGRect 需要我们先把NSRect 转成NSValue
        // 如果rect
        let rect = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        // 更新toolbar 约束
        composeToolbar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(rect.origin.y - SCREENH)
        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            // 更新布局
            self.view.layoutIfNeeded()
        }
    }
    
    // 移除通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // MARK: - 设置导航
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain , target: self, action: "send")
        
        //右侧按钮不能点击
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = titleView
    }
    
    // MARK: - 监听事件
    @objc private func cancel (){
        composeTextView.resignFirstResponder()
        dismissViewControllerAnimated(false, completion: nil)
    }
    
    @objc private func send (){
        print("发送微波")
        
        
        // 如果配图中的数组.count > 0 代表发送有图片微博
        if pictureView.imageList.count > 0{
            upload()
        }else{
            update()
        }
    }
    
    
    // MARK: - 懒加载控件
    private lazy var titleView: UILabel = {
        
        //显示的文字
        let name = HICUserAccountTools.sharedTools.userAccount?.screen_name ?? ""
        //最终显示的文字
        let str = "发微博\n\(name)"
        //获取range
        let range = (str as NSString).rangeOfString(name)
        //富文本
        let attr = NSMutableAttributedString(string: str)
        
        //设置富文本
        attr.addAttributes([NSForegroundColorAttributeName:ThemeColor, NSFontAttributeName: UIFont.systemFontOfSize(13)], range: range)
        
        let lab = UILabel()
        lab.attributedText = attr
        lab.textAlignment = .Center
        lab.numberOfLines = 0
        //设置大小
        lab.sizeToFit()
        return lab
    }()
    
    //textView
    private lazy var composeTextView: HICComposeTxtxView = {
        let view = HICComposeTxtxView()
        
        view.placeholder = "庆历四年春，藤子京谪守巴陵郡，越明年，政通人和，百废具兴。乃重修岳阳楼，增其旧制，属予作文以记之。"
        
        view.delegate = self
        //允许textView上下拖动
        view.alwaysBounceVertical = true
        // 设置font
        view.font = UIFont.systemFontOfSize(16)
        //view.font
        return view
    }()
    
    
    //底部toobar
    private lazy var composeToolbar: HICComposeToolbar = HICComposeToolbar()
    
    //配图
    private lazy var pictureView: HICComposePictureView = HICComposePictureView()
    
    //自定义表情键盘
    private lazy var keyboardView: HICEmoticonKeyboard = {
        let view = HICEmoticonKeyboard()
        view.frame = CGRect(x: 0, y: 0, width: SCREENW, height: 216)
        return view
    }()
    
}

// 处理toolbar按钮点击事件
extension HICComposeViewController{
    func selectImages(){
        let picker = UIImagePickerController()
        
        //设置代理
        picker.delegate = self
        presentViewController(picker, animated: true, completion: nil)
    }
    
    // 切换键盘
    func switchKeyboard(){
        /*
         如果判断当前显示的系统键盘 还是 自定义表情键盘
         */
        // 代表是系统键盘
        if composeTextView.inputView == nil {
            // 切换成自定义键盘
            composeTextView.inputView = keyboardView
            // 告知composeToolbar 键盘样式
            composeToolbar.isEmoticon = true
        }else {
            // 代表是自定义键盘
            // 切换成系统键盘
            composeTextView.inputView = nil
            // 告知composeToolbar 键盘样式
            composeToolbar.isEmoticon = false
        }
        // 刷新inputView
        composeTextView.reloadInputViews()
        // 成为第一响应者
        composeTextView.becomeFirstResponder()
    }
}

extension HICComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//        print(image)
//        composeTextView.backgroundColor = UIColor(patternImage: image)
        
        // 填充图片
        pictureView.addImages(scaleImageOfWidth(600, image: image))
        // 如果实现代理方法 系统将不再帮程序员关闭控制器
        picker.dismissViewControllerAnimated(false, completion: nil)
    }
    
    // 压缩图片
    func scaleImageOfWidth(width: CGFloat,image: UIImage) -> UIImage{
        // 如果传入的图片宽度小于我们制定压缩宽度的话 直接返回
        if width > image.size.width {
            return image
        }
        // 等比例计算出图片的高度
        let height = (width * image.size.height) / image.size.width
        // 创建一个rect
        let rect =  CGRect(x: 0, y: 0, width: width, height: height)
        // 还记得大明湖畔的上下文吗？
        // 01- 开启上下文
        UIGraphicsBeginImageContext(rect.size)
        // 02- 将image 渲染到上下文中
        image.drawInRect(rect)
        // 03- 获取上下文的结果
        let result = UIGraphicsGetImageFromCurrentImageContext()
        // 04- 关闭上下文
        UIGraphicsEndImageContext()
        return result
    }
}

// 发送微博请求
extension HICComposeViewController{
    // 发送文字微博
    func update(){
        HICNetworktools.sharedTools.composeUpdate(composeTextView.text, success: { (response) -> () in
            print("发送成功")
        }) { (error) -> () in
            print("发送失败")
        }
        
    }
    
    // 上传图片且有文字微博
    func upload(){
        
        HICNetworktools.sharedTools.comoposeUpload(composeTextView.text, imageList: pictureView.imageList, success: { (response) -> () in
            print("发送成功")
        }) { (error) -> () in
            print("发送失败")
        }
    }
}

extension HICComposeViewController: UITextViewDelegate{
    // 监听textView 的文字改变
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    func scrollViewDidScroll(scrollView: UIScrollView) {
        composeTextView.resignFirstResponder()
    }
}

extension HICComposeViewController{
    //该方法已经抽取到工具类中
    func demo(){
        //请求url
        let urllString = "ttps://upload.api.weibo.com/2/statuses/upload.json"
        
        // 请求参数
        let params = ["access_token": HICUserAccountTools.sharedTools.accessToken!, "status": composeTextView.text]
        
        // 发送请求
        HICNetworktools.sharedTools.POST(urllString, parameters: params, constructingBodyWithBlock: { (formdata) -> Void in
            // 以表单形式提交（拼接到表单后面提交）
            /*
             data : 将要上传到服务器的二进制文件
             name : 服务器要求规定好文件名称(协议)
             fileName:  上传文件完成后保存到服务器的文件路径 （新浪微博不需要你指定 都会按着自己的方式保存到响应的文件夹中）--- 随意传
             mimeType: 指定上传的二进制文件的格式 application/octet-stream 忽略上传文件的格式
             如果指定为图片 image/jpeg （大类型/ 小类型）
             */
            
            // 遍历数组
            for image in self.pictureView.imageList {
                // image 转二进制
                let data = UIImagePNGRepresentation(image)!
                
                formdata.appendPartWithFileData(data, name: "pic", fileName: "oooo", mimeType: "application/octet-stream")
            }
            
            
            }, progress: nil, success: { (_, response) -> Void in
                print("发送成功")
        }) { (_, error) -> Void in
            print("发送失败")
        }
    }
}

